//
//  HomeViewController.m
//  Audit
//
//  Created by cc on 15-2-6.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "HomeViewController.h"
#import "CarCell.h"
#import "DefectCell.h"
#import "UIImageView+WebCache.h"
#import "AddDefectViewController.h"
#import "PIDrawerViewController.h"
#import "AddDefectViewController.h"
#import "AddCarViewController.h"
#import "CarDetailViewController.h"
#import "DefectDetailViewController.h"
#import "AppDelegate.h"
#import "FlashViewController.h"
#import "QuickQueryViewController.h"
#import "QueryListViewController.h"
#import "AdvancedQueryViewController.h"
#import "GetVinViewController.h"

typedef NS_ENUM(NSUInteger, QueryStatus)
{
    QueryStatusQuickQuery =0,
    QueryStatusAdvancedQuery = 1
};

@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,LCSwipeTableViewCellDelegate,UIAlertViewDelegate,QuickQueryDelegate,AdvancedQueryDelegate>
{
    IBOutlet UITableView *_carsTableView;
    IBOutlet UITableView *_defectTableView;
    IBOutlet UILabel *_titleLabel;
    IBOutlet UIButton *_queryButton;
    IBOutlet UIButton *_addButton;
    
    IBOutlet UIView *_container;
    QueryStatus _queryStatus;

}
@property(nonatomic,retain) QuickQueryViewController *quickQueryVC;
@property(nonatomic,retain) AdvancedQueryViewController *advancedQueryVC;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    delegate.isLoadCarList=NO;
    delegate.isNoNetWork=NO;

    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(setIsLoadCarLsit:) name:NOTIFICATION_IS_LOAD_CAR_LIST object:nil];
    
    self.quickQueryVC = [[QuickQueryViewController alloc] init];
    self.quickQueryVC.delegate = self;
    self.advancedQueryVC = [[AdvancedQueryViewController alloc] init];
    self.advancedQueryVC.delegate = self;
}

//-(void)hiddenFlash
//{
//    [self.flashVC.view removeFromSuperview];
//}

#pragma mark -
#pragma mark notification Methods
- (void)setIsLoadCarLsit:(id)sender
{
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    delegate.isLoadCarList=YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark- UItableview delegate&datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _carsTableView) {
        return [self.listCar count];
    }
    else{
        return [self.selectedCar.listDefect count];
    }
    
//    if (tableView == _carsTableView) {
//        return 2;
//    }
//    else{
//        return 2;
//    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    if (tableView == _carsTableView) {
        //车辆列表
        CarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CarCell"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"CarCell" owner:self options:nil] lastObject];
        }
        
        Car *cellCar=[self.listCar objectAtIndex:[indexPath row]];
        
        cell.carType.text = cellCar.seriesDesc;
        cell.carConfig.text = cellCar.modelDesc;
        cell.carVIN.text = cellCar.vin;

//        cell.carType.text = @"11";
//        cell.carConfig.text = @"11";
//        cell.carVIN.text = @"11";
        cell.tag = 10000 + indexPath.row;
        cell.delegate = self;
        [cell.extendBtn addTarget:self action:@selector(extendCell:) forControlEvents:UIControlEventTouchUpInside];
        
//        UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
//        longPressGr.minimumPressDuration = 2.0;
//        [cell addGestureRecognizer:longPressGr];
        
        return cell;
    }
    else{
        
        //缺陷列表
        DefectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DefectCell"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DefectCell" owner:self options:nil] lastObject];
        }
        cell.delegate = self;
        cell.title.text = ((Defect *)[self.selectedCar.listDefect objectAtIndex:[indexPath row]]).partDesc;
        cell.defectInfo.text = ((Defect *)[self.selectedCar.listDefect objectAtIndex:[indexPath row]]).defectDesc;
        cell.tag = 20000 + indexPath.row;
        
        if (((Defect *)[self.selectedCar.listDefect objectAtIndex:[indexPath row]]).uploadedFile) {
            [cell.picture setImage:((Defect *)[self.selectedCar.listDefect objectAtIndex:[indexPath row]]).uploadedFile];
        }
        else
        {
            [cell.picture setImage:[UIImage imageNamed:@"defaultImg.jpg"]];
        }
        return cell;
        
    }
    return nil;
}

// 长按进入详情页
- (void)tableViewCellDidLongPressed:(LCSwipeTableViewCell *)cell
{
    if ([cell isKindOfClass:[CarCell class]]) {
        
        self.selectedCar = [self.listCar objectAtIndex:cell.tag-10000];
        
        CarDetailViewController *vc = [[CarDetailViewController alloc] init];
        vc.selectedCar = self.selectedCar;
        [self presentViewControllerInFullRect:vc];
    }
    else if ([cell isKindOfClass:[DefectCell class]])
    {
        self.selectedDefect = [self.selectedCar.listDefect objectAtIndex:cell.tag-20000];
        DefectDetailViewController *vc = [[DefectDetailViewController alloc] init];
        vc.selectedDefect = self.selectedDefect;
        [self presentViewControllerInFullRect:vc];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _carsTableView) {
        return 113;
    }
    else{
        return 122;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _carsTableView) {
        self.selectedCar = [self.listCar objectAtIndex:[indexPath row]];
        
        for (int i=0; i<[_carsTableView.visibleCells count]; i++) {
            if (i == [indexPath row]) {
                LCSwipeTableViewCell *cell=[_carsTableView.visibleCells objectAtIndex:[indexPath row]];
                
                [cell setSelected:YES];
            }
            else
            {
                LCSwipeTableViewCell *cell=[_carsTableView.visibleCells objectAtIndex:i];
                
                [cell setSelected:NO];
            }
        }
        
//        CarDetailViewController *vc = [[CarDetailViewController alloc] init];
//        vc.selectedCar = self.selectedCar;
//        [self presentViewControllerInFullRect:vc];
    }
    else
    {
        self.selectedDefect = [self.selectedCar.listDefect objectAtIndex:[indexPath row]];
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _carsTableView) {
        self.selectedCar = [self.listCar objectAtIndex:[indexPath row]];
        
        for (int i=0; i<[_carsTableView.visibleCells count]; i++) {
            if (i == [indexPath row]) {
                LCSwipeTableViewCell *cell=[_carsTableView.visibleCells objectAtIndex:[indexPath row]];
                
                [cell setSelected:YES];
            }
            else
            {
                LCSwipeTableViewCell *cell=[_carsTableView.visibleCells objectAtIndex:i];
                
                [cell setSelected:NO];
            }
        }
        
        //        CarDetailViewController *vc = [[CarDetailViewController alloc] init];
        //        vc.selectedCar = self.selectedCar;
        //        [self presentViewControllerInFullRect:vc];
    }
    else
    {
        self.selectedDefect = [self.selectedCar.listDefect objectAtIndex:[indexPath row]];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (tableView == _carsTableView) {
        UIView *footview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _carsTableView.frame.size.width, 130)];
        //    footview.backgroundColor = [UIColor purpleColor];
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, _carsTableView.frame.size.width-20, 120)];
        [btn setImage:[UIImage imageNamed:@"button_add.png"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(addNewCar:) forControlEvents:UIControlEventTouchUpInside];
        [footview addSubview:btn];
        return footview;
    }
    else if (tableView == _defectTableView) {
        UIView *footview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _defectTableView.frame.size.width, 130)];
        //    footview.backgroundColor = [UIColor purpleColor];
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, _defectTableView.frame.size.width-20, 120)];
        [btn setImage:[UIImage imageNamed:@"button_add.png"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(addCarDefect:) forControlEvents:UIControlEventTouchUpInside];
        [footview addSubview:btn];
        return footview;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (tableView == _carsTableView) {
        return 130;
    }
    return 180;
}


#pragma mark LCSwipeTableViewCellDelegate

- (void)tableViewCell:(LCSwipeTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index {
    if ([cell isKindOfClass:[CarCell class]]) {
        
        Car *cellCar =[self.listCar objectAtIndex:cell.tag-10000];
        
        self.selectedCar=cellCar;
        
        //车辆列表
        switch (index) {
            case 0:
            {
                //编辑
                AddCarViewController *vc=[[AddCarViewController alloc] init];
                vc.doSth=@"edit";
                vc.currentCar=cellCar;
                [self presentViewControllerInFullRect:vc];
                
                vc.editCar=^(Car *editCar){
                    for (int i=0;i<self.listCar.count;i++) {
                        if ([((Car *)[self.listCar objectAtIndex:i]).vehicleId isEqualToString:editCar.vehicleId]) {
                            [self.listCar removeObjectAtIndex:i];
                            [self.listCar insertObject:editCar atIndex:i];
                            break;
                        }
                    }
                    [_carsTableView reloadData];
                };
            }
                break;
            case 1:
            {
                //删除
                
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"确认删除吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
                alert.tag=101;
                [alert show];
            }
                break;
            default:
                break;
        }
    }
    else if ([cell isKindOfClass:[DefectCell class]])
    {
        Defect *cellDefect =[self.selectedCar.listDefect objectAtIndex:cell.tag-20000];
        
        self.selectedDefect=cellDefect;
        
        switch (index) {
            case 0:
            {
                //编辑
                AddDefectViewController *vc=[[AddDefectViewController alloc] init];
                vc.doSth=@"edit";
                vc.currentDefect=cellDefect;
                vc.selectedCar=self.selectedCar;
                [self presentViewControllerInFullRect:vc];
                
                vc.editDefect=^(Defect *editDefect){
                    for (int i=0;i<self.selectedCar.listDefect.count;i++) {
                        if ([((Defect *)[self.selectedCar.listDefect objectAtIndex:i]).auditId isEqualToString:editDefect.auditId]) {
                            [self.selectedCar.listDefect removeObjectAtIndex:i];
                            [self.selectedCar.listDefect insertObject:editDefect atIndex:i];
                            break;
                        }
                    }
                    [_defectTableView reloadData];
                };
            }
                break;
            case 1:
            {
                //删除
                
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"确认删除吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
                alert.tag=102;
                [alert show];
            }
                break;
            default:
                break;
        }
    }
}

- (BOOL)tableViewCellShouldHideUtilityButtonsOnSwipe:(LCSwipeTableViewCell *)cell {
    return YES;
}

#pragma mark LCSwipeTableViewCellDelegate
-(void)deleteCarFinished:(ASIHTTPRequest *)request
{

    if (request.responseStatusCode == 400) {
        //textView.text = @"Invalid code";
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        //textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        for (int i=0;i<self.listCar.count;i++) {
            NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
            
            NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
            
            NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
            
            NSDictionary *strDicData=(NSDictionary *)[strDic objectForKey:@"resultData"];//服务器返回数据字典
            
            if ([flag isEqualToString:@"1001"]) {
                for (int i=0;i<self.listCar.count;i++) {
                    if ([((Car *)[self.listCar objectAtIndex:i]).vehicleId isEqualToString:self.selectedCar.vehicleId]) {
                        [self.listCar removeObjectAtIndex:i];
                        break;
                    }
                }
                [_carsTableView reloadData];
            }
            else if ([flag isEqualToString:@"1002"])
            {
//                [self alertError:msg view:self.view animated:YES afterDelay:1.5];
            }
        }
    }
}

-(void)deleteCarFailed:(ASIHTTPRequest *)request
{
//    [self hideWait];
    [NetworkCheck checkNetwork:self];
}

#pragma mark LCSwipeTableViewCellDelegate
-(void)deleteDefectFinished:(ASIHTTPRequest *)request
{
//    [self hideWait];
    if (request.responseStatusCode == 400) {
        //textView.text = @"Invalid code";
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        //textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        for (int i=0;i<self.listCar.count;i++) {
            NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
            
            NSString *flag=[strDic objectForKey:@"resultCode"];//服务器返回代码
            
            NSString *msg=[strDic objectForKey:@"resultValue"];//服务器返回提示消息
            
            NSDictionary *strDicData=(NSDictionary *)[strDic objectForKey:@"resultData"];//服务器返回数据字典
            
            if ([flag isEqualToString:@"1001"]) {
                for (int i=0;i<self.selectedCar.listDefect.count;i++) {
                    if ([((Defect *)[self.selectedCar.listDefect objectAtIndex:i]).auditId isEqualToString:self.selectedDefect.auditId]) {
                        [self.selectedCar.listDefect removeObjectAtIndex:i];
                        break;
                    }
                }
                [_defectTableView reloadData];
            }
            else if ([flag isEqualToString:@"1002"])
            {
                [self alertError:msg view:self.view animated:YES afterDelay:1.5];
            }
        }
    }
}

-(void)deleteDefectFailed:(ASIHTTPRequest *)request
{
    [self hideWait];
    [NetworkCheck checkNetwork:self];
}

#pragma mark - alert
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==101) {
        if (buttonIndex==1) {
            NSArray *keyArr   = [NSArray arrayWithObjects:@"vehicleId",nil];
            NSArray *valueArr = [NSArray arrayWithObjects:self.selectedCar.vehicleId,nil];
            
            [self showWait:@"" view:self.view];
            [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"vhcDelete.do" finishSelector:@selector(deleteCarFinished:) failSelector:@selector(deleteCarFailed:) delegateObj:self];
        }
    }
    else
    {
        if (buttonIndex==1) {
            NSArray *keyArr   = [NSArray arrayWithObjects:@"auditId",nil];
            NSArray *valueArr = [NSArray arrayWithObjects:self.selectedDefect.auditId,nil];
            
            [self showWait:@"" view:self.view];
            [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"vhcDefectDelete.do" finishSelector:@selector(deleteDefectFinished:) failSelector:@selector(deleteDefectFailed:) delegateObj:self];
        }
    }
}

#pragma mark - Actions
//展开车辆cell
-(void)extendCell:(id)sender
{
    
}

//添加车辆
-(void)addNewCar:(id)sender
{
    AddCarViewController *vc=[[AddCarViewController alloc] init];
    vc.doSth=@"add";
    [self presentViewControllerInFullRect:vc];
    
    vc.addCar=^(Car *newCar){
        if (!self.listCar) {
            self.listCar=[NSMutableArray array];
        }
        [self.listCar insertObject:newCar atIndex:0];
        [_carsTableView reloadData];

        self.selectedCar=[self.listCar objectAtIndex:0];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        
        [_carsTableView scrollToRowAtIndexPath:indexPath
                              atScrollPosition:UITableViewScrollPositionTop animated:YES];
        [_carsTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    };
}

//添加缺陷
-(void)addCarDefect:(id)sender
{
//    if (self.selectedCar) {
        AddDefectViewController *vc = [[AddDefectViewController alloc] init];
        vc.selectedCar=self.selectedCar;
        [self presentViewControllerInFullRect:vc];
        
        vc.addDefect=^(Defect *newDefect){
            if (!self.selectedCar.listDefect) {
                self.selectedCar.listDefect=[NSMutableArray array];
            }
            [self.selectedCar.listDefect addObject:newDefect];
            [_defectTableView reloadData];
        };
//    }
//    else
//    {
//        [self alertError:@"还没有选择车辆哦" view:self.view animated:YES afterDelay:1.5];
//    }
}

#pragma mark - 切换查询和录入页面
//录入
-(IBAction)enteryingAction:(id)sender
{
    UIButton *btn = (UIButton*)sender;
    [self.quickQueryVC.view removeFromSuperview];
    [self.advancedQueryVC.view removeFromSuperview];
    
    _titleLabel.text = @"录入系统";
    
    if (!btn.selected) {
        _addButton.selected = !_addButton.selected;
        _queryButton.selected = !_queryButton.selected;
    }
    
}

//查询
-(IBAction)queryAction:(id)sender
{
    UIButton *btn = (UIButton*)sender;
    if (_queryStatus == QueryStatusAdvancedQuery) {
        
        [self.quickQueryVC.view removeFromSuperview];
        [_container addSubview:self.advancedQueryVC.view];
    }else{
        [self.advancedQueryVC.view removeFromSuperview];
        [_container addSubview:self.quickQueryVC.view];
    }
    
    _titleLabel.text = @"查询系统";
    
    if (!btn.selected) {
        _queryButton.selected = !_queryButton.selected;
        _addButton.selected = !_addButton.selected;
    }
    
}


#pragma mark - 查询系统
-(void)quickQueryAdvancedQuery
{
    //高级查询
    _queryStatus = QueryStatusAdvancedQuery;
    [self.quickQueryVC.view removeFromSuperview];
    [_container addSubview:self.advancedQueryVC.view];
    
}

-(void)advancedQueryQuickQuery
{
    //快速查询
    _queryStatus = QueryStatusQuickQuery;
    [self.advancedQueryVC.view removeFromSuperview];
    [_container addSubview:self.quickQueryVC.view];
}


-(void)beginQueryByCondition:(id)condition
{
    //查询
    QueryListViewController *vc = [[QueryListViewController alloc] init];
    
    vc.carCondition = (Car *)condition;
    
    [self presentViewControllerInFullRect:vc];
    
    
    
//    QueryListViewController *vc = [[QueryListViewController alloc] init];
//    [self presentViewControllerInFullRect:vc];
    
}

-(void)scanAction:(NSString *)text
{
    GetVinViewController * getVinVC = [[GetVinViewController alloc]init];//扫描条形码二维码VC
    getVinVC.doSth=@"getVIN";
    getVinVC.getVinStr=^(NSString *text){
        NSLog(@"%@",text);
//        textFieldVIN.text = vinStr;
    };
    
    [self presentViewControllerInFullRect:getVinVC];
}



@end
